#include "StdAfx.h"
#include "SvrNetRPItem.h"

#include "SvrNetRPCamera.h"
#include "TGSvrNetMan.h"


#define STATISTIC_CHECK_BETTER_TIME 200

SvrNetRPItem::SvrNetRPItem()
{
	m_pCamera     = NULL;
	m_hPacketEvent = NULL;

	m_hSocket    = NULL;
	m_nUseLinkType  = 0;

	m_nItemPos      = 0;

	m_bKeepAlive = true;

	memset(&m_xAddr,0,sizeof(m_xAddr));


	m_hWSAExitEvent = NULL;

#ifdef dkq_write_264
	m_h264 = NULL;
#endif
}

SvrNetRPItem::~SvrNetRPItem(void)
{
	UnInitialize();
}


void SvrNetRPItem::SetRPCamera( SvrNetRPCamera *pCamera ) 
{ 
	m_pCamera = pCamera;

#ifdef dkq_test_svnnet_item
	char sName[50];
	sprintf(sName,"TGSvrNetSDK_%d_ITEM_%x",pCamera->m_nCameraPos,this);
	m_xLog.CreateLogDir(sName,0x1001);
#endif
}

void SvrNetRPItem::SetConnectInfo( TG_CONNECT_INFO *pConnectInfo )
{
	m_xConnectInfo = *pConnectInfo;
}

void SvrNetRPItem::SetSocket( SOCKET hSocket,TG_UDP_ADDR *pAddr ) 
{
	m_hSocket = hSocket; 

	if( NULL != pAddr )
	{
		m_xAddr = *pAddr;
	}

#ifdef dkq_test_svnnet_item
	if( NULL == pAddr )
	{
		SOCKADDR_IN addrPeer;
		int nAddrLen = sizeof(addrPeer);
		getpeername(hSocket, (PSOCKADDR) &addrPeer, &nAddrLen);

		m_xLog.WriteLog( __FILE__,__LINE__,"Initialize %s:%d",inet_ntoa(addrPeer.sin_addr),ntohs(addrPeer.sin_port) );
	}
	else
	{
		m_xLog.WriteLog( __FILE__,__LINE__,"Initialize %s:%d",inet_ntoa(pAddr->xAddr.sin_addr),ntohs(pAddr->xAddr.sin_port) );
	}
#endif
}

int SvrNetRPItem::Initialize(NET_PACKET_HEAD *pRetMsgHead)
{
	MySafeWSACloseEvent(m_hWSAExitEvent);
	m_hWSAExitEvent = ::WSACreateEvent();
	::WSAResetEvent(m_hWSAExitEvent);

	m_hPacketEvent = CreateEvent(NULL,TRUE,FALSE,NULL);

	if( NULL != pRetMsgHead )
	{
		memcpy(&m_xRetMsgHead,pRetMsgHead,sizeof(NET_PACKET_HEAD));
	}



	if( !TGThread::TGThdInit() )
	{
		return TG_ERR_INITERROR;
	}

	return TG_ERR_SUCCESS;
}

int SvrNetRPItem::UnInitialize()
{
	if( NULL != m_hWSAExitEvent )
	{
		::WSASetEvent(m_hWSAExitEvent);
	}
	TGThread::TGThdUnInit();

	MySafeWSACloseEvent(m_hWSAExitEvent);
	MySafeCloseHandle(m_hPacketEvent);

#ifdef dkq_write_264
	if( NULL != m_h264 )
	{
		fclose(m_h264);
		m_h264 = NULL;
	}
#endif
	
	return TG_ERR_SUCCESS;
}



